package cn.tedu.knows.portal.controller;


import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.model.Answer;
import cn.tedu.knows.portal.service.IAnswerService;
import cn.tedu.knows.portal.vo.AnswerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@RestController
@RequestMapping("/v1/answers")
@Slf4j
public class AnswerController {

    @Autowired
    private IAnswerService answerService;

    @PostMapping("")
    //@PreAuthorize("hasAuthority('/question/answer')")
    //hasRole是特指验证角色的指令
    //Role_开头的auth就是角色的标识
    //hasRole验证时可以将Role_省略直接写后面的
    //但是它的判断也不死板hasRole('ROLE-TEACHER')也可以
    @PreAuthorize("hasRole('TEACHER')")
    public Answer postAnswer(
            @Validated AnswerVo answerVo, BindingResult result, @AuthenticationPrincipal UserDetails user
            ){
        log.debug("表单信息"+answerVo);
        if (result.hasErrors()){
            String msg = result.getFieldError().getDefaultMessage();
            throw  new ServiceException(msg);
        }

        return answerService.saveAnswer(answerVo,user.getUsername());
    }

    @GetMapping("/question/{id}")
    public List<Answer> questionAnswers(@PathVariable Integer id){
       return answerService.getAnswerByQuestionId(id);
    }

}
